﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using TERP.HTCServiceClient.Views;
using TERP.HTCServiceClient.Entities.Auth;
using TERP.HTCServiceClient.Common;
using TERP.HTCServiceClient.DbServices;

namespace TERP.HTCServiceClient.Views.Auth
{
    public partial class FrmMapGrpObj : FrmMdiBase
    {
        #region Declarations
        private const string CAPTION_INDEX = "STT";
        private const string CAPTION_GRP_CODE = "Mã nhóm";
        private const string CAPTION_GRP_NAME = "Tên nhóm";
        private const string CAPTION_EDIT_STATUS = "Trạng thái";
        //
        private const string CAPTION_FUNCTION_CODE = "Mã chức năng";
        private const string CAPTION_PARTNER_CODE = "Partner Code";
        private const string CAPTION_FUNCTION_TYPE = "Loại chức năng";
        private const string CAPTION_FUNCTION_NAME = "Tên chức năng";
        //
        private const string FIELD_EDIT_STATUS = "Col_Edit_Status";
        //
        private GroupCollection _grpCollection;
        private DataTable _dtbAllFnc;
        #endregion

        public FrmMapGrpObj()
        {
            InitializeComponent();
        }

        private void FrmMapGrpObj_Load(object sender, EventArgs e)
        {
            InitGrid();
            InitGridItemEditor();
            InitControl();
            SetLanguage();
            this.LoadGroup();
        }

        private void InitControl()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        private void SetLanguage()
        {
            this.grpGroup.Text = "Nhóm";
            this.btnApply.Text = "Lưu";
            this.btnClose.Text = "Đóng";
            this.btnReload.Text = "Tải lại";
			//
			this.lblFunctionBelong.Text = "Chức năng đã gán";
			this.lblFunctionNotBelong.Text = "Chức năng chưa gán";
        }

        /// <summary>
        /// 
        /// </summary>
        private void InitGrid()
        {
            SetGridViewStyle(gviewGroup);
            SetGridViewStyle(gviewFunctionBelong);
            SetGridViewStyle(gviewFunctionNotBelong);
            gviewFunctionBelong.BorderStyle = BorderStyles.Default;
            gviewFunctionNotBelong.BorderStyle = BorderStyles.Default;
            //grid grp
            gridColIdx.Caption = CAPTION_INDEX;
            gridColGrpCode.Caption = CAPTION_GRP_CODE;
            gridColGrpName.Caption = CAPTION_GRP_NAME;
            gridColEditStatus.Caption = CAPTION_EDIT_STATUS;
            //
            gridColIdx.FieldName = TblCommon.Index;
            gridColGrpCode.FieldName = TblGroup.Group_Code;
            gridColGrpName.FieldName = TblGroup.Group_Name;
            gridColEditStatus.FieldName = FIELD_EDIT_STATUS;
            //grid function
            gridColBelongFc.Caption = CAPTION_FUNCTION_CODE;
            gridColBelongFt.Caption = CAPTION_FUNCTION_TYPE;
            gridColBelongFn.Caption = CAPTION_FUNCTION_NAME;
            gridColBelongPartnerCode.Caption = CAPTION_PARTNER_CODE;
            gridColNotBelongFc.Caption = CAPTION_FUNCTION_CODE;
            gridColNotBelongFt.Caption = CAPTION_FUNCTION_TYPE;
            gridColNotBelongFn.Caption = CAPTION_FUNCTION_NAME;
            gridColNotBelongPartnerCode.Caption = CAPTION_PARTNER_CODE;
            //
            gridColBelongFc.FieldName = TblFunctionObject.Object_Code;
            gridColBelongFt.FieldName = TblFunctionObject.Object_Type;
            gridColBelongFn.FieldName = TblFunctionObject.Object_Name;
			gridColBelongPartnerCode.FieldName = TblFunctionObject.Partner_Code;
            gridColNotBelongFc.FieldName = TblFunctionObject.Object_Code;
            gridColNotBelongFt.FieldName = TblFunctionObject.Object_Type;
            gridColNotBelongFn.FieldName = TblFunctionObject.Object_Name;
			gridColNotBelongPartnerCode.FieldName = TblFunctionObject.Partner_Code;
			//
			gridColBelongFc.Visible = false;
			gridColBelongPartnerCode.Visible = false;
			gridColNotBelongFc.Visible = false;
			gridColNotBelongPartnerCode.Visible = false;
			//
			this.SetGridViewBestFitColumn(gviewFunctionBelong);
			this.SetGridViewBestFitColumn(gviewFunctionNotBelong);
			gviewFunctionBelong.DataSourceChanged += new EventHandler(gview_DataSourceChanged);
			gviewFunctionNotBelong.DataSourceChanged += new EventHandler(gview_DataSourceChanged);
        }

        /// <summary>
        /// 
        /// </summary>
        private void InitGridItemEditor()
        {
            reposImgCmbBox.SmallImages = EmbeddedRes.Instance.ImageListEditStatus;
            reposImgCmbBox.Items.Clear();
            reposImgCmbBox.Items.AddRange(new ImageComboBoxItem[] { 
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_NONE, EditStatus.IMG_IDX_STT_NONE), 
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_EDIT, EditStatus.IMG_IDX_STT_EDIT),
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_DELETE, EditStatus.IMG_IDX_STT_DELETE),
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_NEW, EditStatus.IMG_IDX_STT_NEW)
			});
        }

        /// <summary>
        /// 
        /// </summary>
        private void LoadGroup()
        {
            gridGroup.DataSource = null;
            gridFunctionBelong.DataSource = null;
            gridFunctionNotBelong.DataSource = null;
            //
            try
            {
                GroupService grpSv = new GroupService();
                _grpCollection = grpSv.GetGroup();
                FunctionCollection fncCollection = grpSv.GetFunction();
                _dtbAllFnc = fncCollection.DataTableFunction;
            }
            catch (Exception ex)
            {
                Util.ShowExceptionBox(ex);
                return;
            }
            DataTable dtblGrp = _grpCollection.DataTableGroup;
            dtblGrp.Columns.AddRange(new DataColumn[] {
				new DataColumn(TblCommon.Index,typeof(int)),
				new DataColumn(FIELD_EDIT_STATUS,typeof(string))
			});
            int count = 0;
            foreach (DataRow dtRow in dtblGrp.Rows)
            {
                count++;
                dtRow[TblCommon.Index] = count;
                dtRow[FIELD_EDIT_STATUS] = EditStatus.ITEM_VALUE_STT_NONE;
            }
            //
            gridGroup.DataSource = dtblGrp;
            if (count > 0)
                gviewGroup.SelectRow(0);
        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            this.LoadGroup();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void gviewGroup_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            int rowHdl = e.FocusedRowHandle;
            gridFunctionBelong.DataSource = null;
            gridFunctionNotBelong.DataSource = null;
            if (_grpCollection == null)
                return;
            string grpCode = Convert.ToString(gviewGroup.GetRowCellValue(rowHdl, TblGroup.Group_Code));
            //
            DataTable dtblFncBelong = null;
            Group grp = _grpCollection.FindGroup(grpCode);
            if (grp == null)
                return;
            dtblFncBelong = grp.ListFunction.DataTableFunction;
            //
            gridFunctionBelong.DataSource = dtblFncBelong;
            //
            List<string> lstFcBelong = new List<string>();
            foreach (DataRow dtRow in dtblFncBelong.Rows)
            {
                if (dtRow.RowState == DataRowState.Deleted)
                    continue;
                lstFcBelong.Add((string)dtRow[TblFunctionObject.Object_Code]);
            }
            //
            DataTable dtblFncNotBelong = _dtbAllFnc.Copy();
            foreach (string fncCode in lstFcBelong)
            {
                foreach (DataRow dtRow in dtblFncNotBelong.Rows)
                {
                    string tmp = (string)dtRow[TblFunctionObject.Object_Code];
                    if (fncCode.Equals(tmp))
                    {
                        dtblFncNotBelong.Rows.Remove(dtRow);
                        break;
                    }
                }
            }
            gridFunctionNotBelong.DataSource = dtblFncNotBelong;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="gviewFrom"></param>
        /// <param name="gviewTo"></param>
        private void MoveSelectRow(GridView gviewFrom, GridView gviewTo)
        {
            foreach (int rowHandle in gviewFrom.GetSelectedRows())
            {
                string fc = (string)gviewFrom.GetRowCellValue(rowHandle, TblFunctionObject.Object_Code);
                string ft = (string)gviewFrom.GetRowCellValue(rowHandle, TblFunctionObject.Object_Type);
                string fn = (string)gviewFrom.GetRowCellValue(rowHandle, TblFunctionObject.Object_Name);
				string partnerCode = (string)gviewFrom.GetRowCellValue(rowHandle, TblFunctionObject.Partner_Code);
                DataTable dtblTo = (DataTable)gviewTo.GridControl.DataSource;
                DataRow dtRow = dtblTo.NewRow();
                dtRow[TblFunctionObject.Object_Code] = fc;
                dtRow[TblFunctionObject.Object_Type] = ft;
                dtRow[TblFunctionObject.Object_Name] = fn;
				dtRow[TblFunctionObject.Partner_Code] = partnerCode;
                //
                dtblTo.Rows.Add(dtRow);
            }
            //
            gviewFrom.DeleteSelectedRows();
            this.SetCurrentGroupEditState();
        }

        /// <summary>
        /// 
        /// </summary>
        private void SetCurrentGroupEditState()
        {
            DataRow dtRow = gviewGroup.GetFocusedDataRow();
            if (dtRow != null)
                dtRow[FIELD_EDIT_STATUS] = EditStatus.ITEM_VALUE_STT_EDIT;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            this.MoveSelectRow(gviewFunctionNotBelong, gviewFunctionBelong);
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            this.MoveSelectRow(gviewFunctionBelong, gviewFunctionNotBelong);
        }

        private void btnAddAll_Click(object sender, EventArgs e)
        {
            gviewFunctionNotBelong.SelectAll();
            this.MoveSelectRow(gviewFunctionNotBelong, gviewFunctionBelong);
        }

        private void btnRemoveAll_Click(object sender, EventArgs e)
        {
            gviewFunctionBelong.SelectAll();
            this.MoveSelectRow(gviewFunctionBelong, gviewFunctionNotBelong);
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            List<string> lstGrpCode = new List<string>();
            DataTable dtbMapGrpObj = new DataTable();
            dtbMapGrpObj.Columns.AddRange(new DataColumn[]{
				new DataColumn(TblGroup.Group_Code),
				new DataColumn(TblFunctionObject.Object_Code),
				new DataColumn(TblFunctionObject.Partner_Code)
			});
            //
            for (int rowHandle = 0; rowHandle < gviewGroup.RowCount; rowHandle++)
            {
                string grpCode = (string)gviewGroup.GetRowCellValue(rowHandle, TblGroup.Group_Code);
                string editStatus = (string)gviewGroup.GetRowCellValue(rowHandle, FIELD_EDIT_STATUS);
                if (editStatus.Equals(EditStatus.ITEM_VALUE_STT_EDIT))
                {
                    lstGrpCode.Add(grpCode);
                    Group grp = _grpCollection.FindGroup(grpCode);
                    DataTable dtblFncBelong = grp.ListFunction.DataTableFunction;
                    foreach (DataRow dtRow in dtblFncBelong.Rows)
                    {
                        if (dtRow.RowState == DataRowState.Deleted)
                            continue;
                        DataRow dtRowMap = dtbMapGrpObj.NewRow();
                        dtRowMap[TblFunctionObject.Object_Code] = dtRow[TblFunctionObject.Object_Code];
						dtRowMap[TblFunctionObject.Partner_Code] = dtRow[TblFunctionObject.Partner_Code];
                        dtRowMap[TblGroup.Group_Code] = grpCode;
                        dtbMapGrpObj.Rows.Add(dtRowMap);
                    }
                }
            }
            //
            if (lstGrpCode.Count == 0)
                return;
            try
            {
                GroupService grpSv = new GroupService();
                DataSet dsMap = new DataSet();
                dsMap.Tables.Add(dtbMapGrpObj);
                grpSv.MapObjectToGroup(lstGrpCode, dsMap);
                this.LoadGroup();
            }
            catch (Exception ex)
            {
                Util.ShowExceptionBox(ex);
            }
        }

		private void splitContainerControl_Panel2_SizeChanged(object sender, EventArgs e)
		{
			int borderPadding = 6;
			int controlSpacing = 20;
			int btnWidth = 88;
			int usedWidth = borderPadding * 2 + controlSpacing * 2 + btnWidth;
			int widthParent = splitContainerControl.Panel2.Width;
			int widthGrid = (widthParent - usedWidth) / 2;
			//
			int xOffset = borderPadding;
			gridFunctionBelong.Left = xOffset;
			gridFunctionBelong.Width = widthGrid;
			//
			xOffset += widthGrid + controlSpacing;
			btnAdd.Left = xOffset;
			btnAddAll.Left = xOffset;
			btnRemove.Left = xOffset;
			btnRemoveAll.Left = xOffset;
			//
			xOffset += controlSpacing + btnWidth;
			lblFunctionNotBelong.Left = xOffset;
			gridFunctionNotBelong.Left = xOffset;
			gridFunctionNotBelong.Width = widthGrid;
			//button y
			int buttonSpacing = 6;
			int heightBtn = 26;
			int usedHeight = 4 * 26 + 3 * buttonSpacing;
			int heightGrid = gridFunctionBelong.Height;
			int yOffset = (heightGrid - usedHeight) / 2;
			if (yOffset < gridFunctionBelong.Top)
				yOffset = gridFunctionBelong.Top;
			btnAdd.Top = yOffset;
			yOffset += heightBtn + buttonSpacing;
			btnRemove.Top = yOffset;
			yOffset += heightBtn + buttonSpacing;
			btnAddAll.Top = yOffset;
			yOffset += heightBtn + buttonSpacing;
			btnRemoveAll.Top = yOffset;
		}

    }
}
